package com.young.launch_task_init

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.ProgressBar
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatTextView
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.*
import java.lang.Runnable

/**
 * Author：young
 * .
 * Time： 1/4/2023 下午6:17 周六
 * .
 * Desc：启动页面
 */
class LaunchActivity : AppCompatActivity() {

    private val progressBar by lazy {
        findViewById<ProgressBar>(R.id.progressBar)
    }

    private val progressTv by lazy {
        findViewById<AppCompatTextView>(R.id.tv_progress)
    }


    private val countDownTv by lazy {
        findViewById<AppCompatTextView>(R.id.tv_count_down)
    }

    // 倒计时 3 s
    private var countDown = 3

    // 任务是否初始化完成
    private var isTaskInitCompleted = false

    override fun onCreate(savedInstanceState: Bundle?) {
        supportActionBar?.hide()
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_launch)
        registerTaskProgressListener()
        showCountDown()
    }


    /**
     * 注册任务执行进度监听
     */
    private fun registerTaskProgressListener() {
        // 注册任务执行进度监听
        App.taskProgressListener = { progress, maxProgress ->
            Log.e("young_test", "progress=${progress} maxProgress=${maxProgress}")
            showProgress(progress, maxProgress)


        }

        // 所有任务完成监听
        App.allTaskCompletedListener = Runnable {
            Log.e("young_test", "准备进入主页")
            isTaskInitCompleted = true
            showProgress(progressBar.max, progressBar.max)
            openMainPage()
        }
    }

    /**
     * 显示进度条
     * @param progress 当前进度
     * @param maxProgress 最大进度
     */
    private fun showProgress(progress: Int, maxProgress: Int) {
        progressBar.max = maxProgress
        progressBar.progress = progress
        progressTv.text = "${progress}/${maxProgress}"
    }

    /**
     * 显示倒计时
     */
    @SuppressLint("SetTextI18n")
    private fun showCountDown() {
        lifecycleScope.launch(Dispatchers.IO) {
            do {
                withContext(Dispatchers.Main) {
                    countDownTv.text = "${countDown}s"
                }
                if (countDown == 0) {
                    openMainPage()
                    break
                }
                delay(1000)


                countDown--
            }while (isActive)

        }
    }

    /**
     * 打开主页
     */
    private fun openMainPage() {
        if (countDown == 0 && isTaskInitCompleted) {
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
            finish()
        }

    }
}